import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  HddOutlined,
  LoadingOutlined,
  SearchOutlined,
  SyncOutlined,
} from "@ant-design/icons";
import { useRequest } from "@umijs/hooks";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  message,
  Modal,
  Popover,
  Select,
  Table,
  Tag,
  TreeSelect,
} from "antd";
import { Store } from "rc-field-form/lib/interface";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import TableToolbar from "../../../components/TableSetting/TableToolbar";
import { fetchRequest } from "../../../utils/Request";
import { url } from "../../../utils/url";
import "../index.css";
import AddChannelStaff from "./AddChannelStaff";
import EditChannelStaffInformation from "./EditChannelStaffInformation";
import { getOriginString, getSecretString } from "../../../utils/encrypt";

interface Detail {
  visible: boolean;
  content: any;
}

//请求参数
interface tableRequestParam {
  name: null | undefined | string;
  phone: null | undefined | string;
  channelName: null | undefined | string;
  index: number;
  num: number;
}

interface CheckParams {
  Id: string;
}

export default function ChannelStaffManageTable() {
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "手机号",
      dataIndex: "phone",
      key: "phone",
      render: (record: any) => {
        return getOriginString(record);
      },
    },
    {
      title: "渠道名称",
      dataIndex: "channelName",
      key: "channelName",
    },
    {
      title: "新增时间",
      dataIndex: "startDate",
      key: "startDate",
    },
    {
      title: "操作",
      render: (record: any) => (
        <span onClick={(e) => e.stopPropagation()}>
          <Tag
            className="tags-hover"
            color="#f50"
            onClick={(e) => {
              // deleteStudentCard.run({"id": record.id})
              // checkAccess.run({ Id:record.Id})
              showDeleteConfirm(record);
            }}
            icon={<DeleteOutlined />}
          >
            删除
          </Tag>

          <Tag
            className="tags-hover"
            color="#00BFFF"
            onClick={() => seteditVisible({ visible: true, content: record })}
            icon={<EditOutlined />}
          >
            修改
          </Tag>
        </span>
      ),
    },
  ];

  const [tableRequestParam, setTableRequestParam] = useState<tableRequestParam>(
    { name: "", phone: "", channelName: "", index: 1, num: 10 }
  );

  const [tableData, setTableData] = useState<any>([]);

  const [addVisible, setaddVisible] = useState<boolean>(false);

  const [columnsKey, setcolumnsKey] = useState<any[]>([]);

  const [realColumns, setrealColumns] = useState<any[]>([]);

  const [editVisible, seteditVisible] = useState<{
    visible: boolean;
    content: any;
  }>({ visible: false, content: null });

  const [form] = Form.useForm();

  function showDeleteConfirm(info: any) {
    Modal.confirm({
      title: "确定删除?",
      icon: <ExclamationCircleOutlined />,
      content: info.message,
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        deleteChannelStaff.run({
          id: info.id,
        });
      },
    });
  }

  const deleteChannelStaff = useRequest(deleteChannelStaffRequest, {
    loadingDelay: 200,
    manual: true,
  });

  //删除的请求函数
  async function deleteChannelStaffRequest(params: any) {
    // console.log(params)
    try {
      const json = await fetchRequest(url.DELETE_CHANNEL_STAFF, params);
      if (json.success) {
        message.destroy();
        message.success("删除成功!");
        if (
          tableData.count > tableRequestParam.num &&
          tableData.count - 1 ===
            tableRequestParam.index * tableRequestParam.num
        ) {
          setTableRequestParam({
            ...tableRequestParam,
            index: tableRequestParam.index - 1,
          });
        } else {
          getChannelStaff.run(tableRequestParam);
        }
      } else {
        message.destroy();
        message.error(json.errorMsg);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  //点击搜索按钮
  function handleFinish(values: any) {
    // console.log("搜索参数")
    // console.log(values)
    setTableRequestParam({
      name: typeof values.name === "undefined" ? "" : values.name,
      phone:
        typeof values.phone === "undefined"
          ? ""
          : getSecretString(values.phone),
      channelName:
        typeof values.channelName === "undefined" ? "" : values.channelName,
      index: 1,
      num: 10,
    });
  }

  //点击重置按钮
  function handleReset() {
    form.resetFields();
    setTableRequestParam({
      name: "",
      phone: "",
      channelName: "",
      index: 1,
      num: 10,
    });
  }

  //递归删除空的children
  function deleteEmpty(arr: any[]) {
    arr.forEach((item) => {
      if (item.children.length === 0) {
        delete item.children;
      } else {
        deleteEmpty(item.children);
      }
    });
  }

  //查询框
  const searchForm = (
    <Card className="search-form">
      {" "}
      <Form
        form={form}
        layout="inline"
        onFinish={handleFinish}
        onReset={handleReset}
      >
        <Form.Item className="form-control-item" name="name" label="姓名">
          <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item" name="phone" label="电话">
          <Input className="search-form-item" />
        </Form.Item>

        <Form.Item
          className="form-control-item"
          name="channelName"
          label="渠道名称"
        >
          <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item">
          <Button
            key="1"
            type="primary"
            icon={<SearchOutlined />}
            htmlType="submit"
            style={{ marginRight: "8px" }}
          >
            搜索
          </Button>
          <Button key="2" icon={<SyncOutlined />} htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );

  const [detail, setDetail] = useState<Detail>({
    visible: false,
    content: null,
  });

  //监听变化
  useEffect(() => {
    const realColumns = columns.filter(
      (item) => columnsKey.indexOf(item.key) !== -1
    );
    setrealColumns(realColumns);
  }, [columnsKey]);

  //点击行的时候
  function onRowClick(value: any) {
    // console.log(value)
    setDetail({ visible: true, content: value });
  }

  //当列设置改变的时候
  function onColumnsChange(checkedList: any[]) {
    // console.log(checkedList)
    setcolumnsKey(checkedList);
  }

  //递归修改item的key
  function disableSelect(arr: any[]) {
    // console.log("进入disableselect")
    arr.map((item) => {
      // delete item.disabled
      item.key = item.deptID;
      item.value = item.deptID;
      if (
        typeof item.children === "undefined" ||
        item.children === null ||
        item.children.length === 0
      ) {
        return;
      } else {
        disableSelect(item.children);
      }
    });
  }

  const dispatch = useDispatch();

  //获取门禁人员信息管理的table
  const getChannelStaff = useRequest(getChannelStaffRequest, {
    loadingDelay: 200,
    manual: true,
  });

  //异步请求的接口
  async function getChannelStaffRequest(params: tableRequestParam) {
    // console.log("接口请求参数");
    // console.log(params);
    try {
      const json = await fetchRequest(url.GET_CHANNEL_STAFF, params);
      if (json.success) {
        setTableData(json.data);
      } else {
        message.error(json.errorMsg);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  //监听请求参数的变化 变化之后进行请求
  useEffect(() => {
    getChannelStaff.run(tableRequestParam);
  }, [tableRequestParam]);

  //点击刷新按钮
  function onRefresh() {
    getChannelStaff.run(tableRequestParam);
  }

  //点击新增按钮
  function onAdd() {
    setaddVisible(true);
  }

  //新增成功
  function addSuccess() {
    message.destroy();
    message.success("新增成功!");
    setaddVisible(false);
    getChannelStaff.run(tableRequestParam);
  }

  //新增成功
  function onaddSuccess() {
    message.destroy();
    message.success("修改成功!");
    seteditVisible({ ...editVisible, visible: false });
    getChannelStaff.run(tableRequestParam);
  }

  //点击分页的时候
  function handlePageChange(page: number) {
    setTableRequestParam({
      ...tableRequestParam,
      index: page,
    });
  }

  return (
    <div>
      {searchForm}
      <Card className="search-form-table">
        <TableToolbar
          tableName="渠道人员管理表"
          columns={columns}
          onColumnsChange={onColumnsChange}
          onRefresh={onRefresh}
          onAdd={onAdd}
        />
        <Table
          loading={getChannelStaff.loading}
          pagination={{
            hideOnSinglePage: true,
            simple: true,
            pageSize: 10,
            onChange: handlePageChange,
            total: tableData.total,
            current: tableRequestParam.index,
          }}
          onRow={(record: any) => {
            return { onClick: (e) => onRowClick(record) };
          }}
          rowKey={(record: any) => record.id}
          columns={realColumns}
          // dataSource={data}
          dataSource={tableData.rows}
        />
      </Card>
      <Drawer
        width="60%"
        destroyOnClose
        visible={addVisible}
        title="新增渠道人员"
        onClose={() => setaddVisible(false)}
      >
        <AddChannelStaff addSuccess={addSuccess} />
      </Drawer>
      <Drawer
        width="60%"
        destroyOnClose
        visible={editVisible.visible}
        title="修改人员信息"
        onClose={() => seteditVisible({ ...editVisible, visible: false })}
      >
        <EditChannelStaffInformation
          info={editVisible.content}
          onaddSuccess={onaddSuccess}
        />
      </Drawer>
    </div>
  );
}
